package com.example.beautymakeup.service.impl;

import com.example.beautymakeup.dao.UserDao;
import com.example.beautymakeup.domain.PageBean;
import com.example.beautymakeup.domain.entry.LoginUser;
import com.example.beautymakeup.pojo.User;
import com.example.beautymakeup.service.UserService;
import com.example.beautymakeup.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;
//  登陆时候用的
    public User getByOpenId(String openId) {
        return userDao.getByOpenId(openId);
    }

    @Override
    public LoginUser getById(String token) throws Exception {
        Claims claims = JwtUtil.parseJWT(token);
        String subject = claims.getSubject();
        User byId = userDao.getById(subject);
        if (byId == null){
            return null;
        }
        LoginUser loginUser = new LoginUser();
        loginUser.setUserName(byId.getUserName());
        loginUser.setUserImage(byId.getUserImage());
        return loginUser;
    }

    public boolean save(User user) {
        return userDao.save(user) == 1;
    }

    public int updateUser(String token,User user) throws Exception {
        Claims claims = JwtUtil.parseJWT(token);
        String subject = claims.getSubject();
        user.setUid(Integer.valueOf(subject));
        return userDao.updateUser(user);
    }

    @Override
    public PageBean<User> getUserAll(String token,int page,int size) throws Exception {
        Claims claims = JwtUtil.parseJWT(token);
        String subject = claims.getSubject();
        if ("admin".equals(subject)){
            PageBean<User> pageBean = new PageBean<>();
            pageBean.setRows(userDao.getUserAll((page-1)*size,size));
            pageBean.setTotalCount(userDao.getUserAllTotal());
            return pageBean;
        }
        else {
            return null;
        }

    }

    @Override
    public boolean banByUId(String token,User user) throws Exception {
        Claims claims = JwtUtil.parseJWT(token);
        String subject = claims.getSubject();
        if ("admin".equals(subject)){
            return userDao.banByUId(user) == 1;
        }
        else {
            return false;
        }
    }
}
